'''
dionysus - a web based dialogue management framework
Copyright (C) 2011  Eugeniu Costetchi <eugeniu.costetchi (at) tudor.lu>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
'''


from django.utils import simplejson
from DialogueManager.Dialoguer import Dialoguer, DialoguePool
import logging
from django.contrib.auth.decorators import login_required
from dajaxice.decorators import dajaxice_register
from DialogueManager.Context import Context
from DialogueManager.pool import DialoguerPool
#import thread

#===============================================================================
# keeping a dictionary of session_key:dialoguer_instance
#===============================================================================
#dialoguers = {}
#lock  = thread.allocate_lock()
#===============================================================================
# the timers for each session
#===============================================================================
#timers = {}

#TIMEOUT = 3600;
#TIC = 90;

logger = logging.getLogger(__name__)
#===============================================================================
# get_dialoguer
# TODO: on logout, remove the dialoguer from the list
# session.session_key is changing unexpectedly, aparently it is some kind of site protection
# injecting a self made id
#===============================================================================
def get_dialoguer(request):
    if not DialoguerPool.exists(request.session.session_key):
        #lock.acquire()
        DialoguerPool.set(request.session.session_key,Dialoguer())
        #lock.release()
        logger.info("New dialoguer created ("+str(DialoguerPool.size())+" in pool) for session :"+str(request.session.session_key))
    else:
        logger.info("Accessed an existent dialoguer")
    #timers[request.session.session_key] = time.time()
    return DialoguePool.get(request.session.session_key)

#===============================================================================
# a cleaning mechanism for zomby dialoguers; every 'TIC' seconds the dialogues will 
# be checked whether 'TIMEOUT' seconds passed since last call from the client
#===============================================================================
#@DeprecationWarning
#def clean_pool(request):
#    logger.info("Cleaning the dialoguers pool")
#    threading.Timer(TIC, clean_pool,[request]).start()
#    now = time.time()
#    sessions = timers.keys()
#    for i in sessions:
#        if now-timers[i] > TIMEOUT:
#            try:
#                del timers[i]
#                del dialoguers[i]
#            except KeyError:
#                logger.error("Tried to delete a session that does not exist")

#===============================================================================
# talk
#===============================================================================
@dajaxice_register
@login_required
def update(request, text):
    reply = ["Oops! My mind went blank ..."]
    try:
        d = get_dialoguer(request) 
        d.listen(utterance=text)
        d.process(consume_top_listen_action=True)
        reply = d.say()
    except Exception, e:
        logger.error('Exception in Dialoguer operations ' + str(e))
        
    return simplejson.dumps({'message':reply})

#===============================================================================
# suggestion_list
#===============================================================================
@dajaxice_register
@login_required
def suggestion_list(request, term):
    d = get_dialoguer(request).dialogue_context[Context.DICTIONARY]
    data = d.get_words(term)
    #logger.info("suggestion list based on term:"+term)
    return simplejson.dumps(data)

#===============================================================================
# touch the server so the dialogues in the serverside do not get deleted
#===============================================================================
#@dajaxice_register
#def touch(request):
#    get_dialoguer(request)
#    return simplejson.dumps('OK')

def before_leave(request):
    #global dialoguers
    logger.error("Deleting the dialoguer from session :"+request.session.session_key)
#    try:
#        del dialoguers[request.session.session_key]
#    except KeyError:
#        logger.error("Could not delete the dialoguer with session :"+request.session.session_key)
    return simplejson.dumps('Bye')